package com.xjj.link;


import com.xjj.ListNode;

public class E0021MergeTwoSortedLists {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode protect = new ListNode(-101);
        ListNode head = protect;
        ListNode tmp = null;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                tmp = l2;
                l2 = l2.next;
                head = addNode(head, tmp);
            } else {
                tmp = l1;
                l1 = l1.next;
                head = addNode(head, tmp);
            }
        }
        if (l1 != null) {
            head = addNode(head, l1);
        }
        if (l2 != null) {
            head = addNode(head, l2);
        }
        return protect.next;
    }

    private ListNode addNode(ListNode head, ListNode node) {
        head.next = node;
        return node;
    }
}
